import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { AppEnvelope } from '../model/message';
import { environment } from '../../environments/environment';



@Injectable(
  { providedIn: 'root' },
)
export class RequestService {

  constructor(
    private http: HttpClient,
  ) { }

  post<T>(url: string, body?: any, param?: HttpParams): Observable<T> {
    return this.request<T>('POST', url, { body, params: param });
  }

  get<T>(url: string, param?: HttpParams): Observable<T> {
    return this.request<T>('GET', url, { params: param });
  }

  private request<T>(
    method: string,
    url: string,
    options?: {
      body?: any;
      headers?: HttpHeaders | { [header: string]: string | string[]; };
      params?: HttpParams | { [param: string]: string | string[]; };
      reportProgress?: boolean;
      withCredentials?: boolean;
    }): Observable<T> {
    const requestURL = environment.server.concat(url);
    return this.http.request<AppEnvelope<T>>(
      method,
      requestURL,
      {
        body: options?.body,
        headers: options?.headers,
        reportProgress: options?.reportProgress,
        params: options?.params,
        responseType: 'json',
        withCredentials: options?.withCredentials,
        observe: 'body'
      }
    ).pipe(
      map(message => {
        if (message.code !== 200) {
          console.error(message);
          throw new Error('服务器状态错误');
        }
        return message.data;
      }),
      catchError(
        (error) => {
          if (error.error instanceof ErrorEvent) {
            console.error('网络连接错误', error.error.message);
          } else {
            console.error(`服务器错误！状态码:${error.status},body:`, error.error);
          }
          return throwError('服务器错误');
        }
      ),
    );
  }
}
